package com.rc.saas.mini.service.member;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rc.saas.mini.common.constant.WebConstant;
import com.rc.saas.mini.mapper.market.MarketActivityMemberMapper;
import com.rc.saas.mini.mapper.market.MarketActivityTicketMapper;
import com.rc.saas.mini.mapper.member.MemberTicketMapper;
import com.rc.saas.mini.mapper.ticket.TenantTicketSendRecordMapper;
import com.rc.saas.mini.model.market.MarketActivity;
import com.rc.saas.mini.model.market.MarketActivityMember;
import com.rc.saas.mini.model.market.MarketActivityTicket;
import com.rc.saas.mini.model.market.MarketActivityTicketExample;
import com.rc.saas.mini.model.member.MemberInfo;
import com.rc.saas.mini.model.member.MemberTicket;
import com.rc.saas.mini.model.member.MemberTicketExample;
import com.rc.saas.mini.model.recharge.RechargeOrder;
import com.rc.saas.mini.model.tenant.TenantTicketSendRecord;
import com.rc.saas.mini.model.tenant.TenantTicketType;
import com.rc.saas.mini.service.market.MarketActivityMemberService;
import com.rc.saas.mini.service.market.MarketActivityService;
import com.rc.saas.mini.service.ticket.TenantTicketTypeService;
import com.rc.saas.mini.vo.member.MemberTicketVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author wangzhengwei
 * @create 2021/4/25
 */
@Service
public class MemberTicketServiceImpl implements MemberTicketService {
    @Autowired
    private MemberTicketMapper memberTicketMapper;

    @Autowired
    private TenantTicketTypeService tenantTicketTypeService;

    @Autowired
    private MarketActivityService marketActivityService;

    @Autowired
    private MarketActivityMemberService marketActivityMemberService;
    @Autowired
    private MemberInfoService memberInfoService;

    @Autowired
    private MarketActivityTicketMapper marketActivityTicketMapper;
    @Autowired
    private TenantTicketSendRecordMapper tenantTicketSendRecordMapper;

    @Autowired
    private MarketActivityMemberMapper marketActivityMemberMapper;

    @Override
    public MemberTicketMapper getMapper() {
        return memberTicketMapper;
    }

    @Override
    public PageInfo<MemberTicketVo> listPageTicket(MemberInfo member, String usingStatus, Integer pageNo, Integer pageSize) {
        PageHelper.startPage(pageNo, pageSize);
        List<MemberTicketVo> memberTickets = memberTicketMapper.listMemberTicketByMember(member.getTenantCode(), member.getMemberId(), usingStatus, null);
        return new PageInfo<>(memberTickets);
    }

    @Override
    public PageInfo<MemberTicketVo> listPageExpiredTicket(MemberInfo member, Integer pageNo, Integer pageSize) {
        PageHelper.startPage(pageNo, pageSize);
        List<MemberTicketVo> list = memberTicketMapper.listExpiredTicket(member.getTenantCode(), member.getMemberId());
        return new PageInfo<>(list);
    }

    //@Override
    //public void SendCoupons(Long ticketTypeId, Long ticketSendRecordId, Long memberId, String tenantCode) {
    //    TenantTicketType tenantTicketType = tenantTicketTypeService.selectByPrimaryKey(ticketTypeId);
    //    MemberTicket memberTicket = new MemberTicket();
    //    memberTicket.setTenantCode(tenantCode);
    //    memberTicket.setMemberId(memberId);
    //    memberTicket.setTicketTypeId(ticketTypeId);
    //    memberTicket.setTicketSource("1");
    //    memberTicket.setTicketSendRecordId(ticketSendRecordId);
    //    memberTicket.setStatus("0");
    //    memberTicket.setGainTime(new Date());
    //    memberTicket.setCreatedBy("Wx" + tenantCode);
    //    memberTicket.setCreatedTime(new Date());
    //    if ("1".equals(tenantTicketType.getEffectType())) {
    //        //生效方式 0指定N天有效 1指定日期生效
    //        memberTicket.setEndTime(tenantTicketType.getEffectEndDate());
    //    } else if ("0".equals(tenantTicketType.getEffectType())) {
    //        memberTicket.setEndTime(DateUtils.addDays(new Date(),tenantTicketType.getEffectDay()));
    //    }
    //    memberTicketMapper.insertSelective(memberTicket);
    //}

    @Override
    public void insertActivityTicket(MemberInfo memberInfo, RechargeOrder rechargeOrder) {
        //查询当前活动下的 剩余次数 的的优惠活动 且符合用户身份的
        // sendType 赠送对象 0 新用户 1邀请者 2普通用户 3企业用户 4全部 默认 0
        // rewardType 0 赠送优惠券 1 消费返利 2充值送优惠券 3充值送现金 4充值减免
        // activityType 0 新用户注册优惠 1 充值送活动
        // paymentType 0:微信支付 1:支付宝 U:银联支付类型,C 农行
        BigDecimal amount = rechargeOrder.getAmount();
        String paymentType = rechargeOrder.getPaymentType();
        //充值送优惠券
        List<MarketActivity> activityList = marketActivityService.listCurrentActivity(memberInfo.getTenantCode(),
                "0".equals(memberInfo.getMemberType()) ? "2" : "3", "2", "1");
        //MarketActivity marketActivity = null;
        List<MarketActivity> marketActivityList = new ArrayList<>();
        switch (paymentType) {
            case "0":
                //marketActivity = activityList.stream().filter(activity->activity.getWxPay()==1).findFirst().orElseGet(() -> null);
                marketActivityList = activityList.stream().filter(activity -> activity.getWxPay() == 1).collect(Collectors.toList());
                break;
            case "1":
                //marketActivity = activityList.stream().filter(activity->activity.getAliPay()==1).findFirst().orElseGet(() -> null);
                marketActivityList = activityList.stream().filter(activity -> activity.getAliPay() == 1).collect(Collectors.toList());
                break;
            case "U":
                //marketActivity = activityList.stream().filter(activity->activity.getUnPay()==1).findFirst().orElseGet(() -> null);
                marketActivityList = activityList.stream().filter(activity -> activity.getUnPay() == 1).collect(Collectors.toList());
                break;
            case "C":
                //marketActivity = activityList.stream().filter(activity->activity.getAbcPay()==1).findFirst().orElseGet(() -> null);
                marketActivityList = activityList.stream().filter(activity -> activity.getAbcPay() == 1).collect(Collectors.toList());
                break;
            default:
        }
        if (marketActivityList.size() > 0) {
            //多个活动
            for (MarketActivity marketActivity : marketActivityList) {
                //参与活动次数
                int count = marketActivityMemberService.countByMarketActivityId(marketActivity.getMarketActivityId(), memberInfo.getMemberId());
                if (count < marketActivity.getMaxDiscountCount().intValue()) {

                    MarketActivityTicketExample marketActivityTicketExample = new MarketActivityTicketExample();
                    marketActivityTicketExample.createCriteria().andMarketActivityIdEqualTo(marketActivity.getMarketActivityId())
                            .andRequireAmountLessThanOrEqualTo(amount).andUpperLimitAmoutGreaterThan(amount);
                    marketActivityTicketExample.setOrderByClause(" require_amount desc");
                    //多张优惠券
                    List<MarketActivityTicket> marketActivityTicketList = marketActivityTicketMapper.selectByExample(marketActivityTicketExample);
                    if (marketActivityTicketList.size() > 0) {
                        MarketActivityMember marketActivityMember = marketActivityMemberAdd(memberInfo, marketActivityTicketList.get(0), rechargeOrder.getRechargeOrderId());
                        for (MarketActivityTicket marketActivityTicket : marketActivityTicketList) {
                            if (marketActivityTicket != null) {
                                TenantTicketType tenantTicketType = tenantTicketTypeService.selectUsedTicket(marketActivityTicket.getTicketTypeId());
                                if (tenantTicketType != null) {
                                    allTicketDataAdd(memberInfo, tenantTicketType, marketActivityTicket, rechargeOrder.getRechargeOrderId(), marketActivityMember);
                                }
                            }

                        }
                    }
                }
            }

        }

    }

    @Override
    public PageInfo<MemberTicketVo> listPageTicketByElecStationId(MemberInfo member, Long elecStationId, String usingStatus, Integer pageNo, Integer pageSize) {
        PageHelper.startPage(pageNo, pageSize);
        List<MemberTicketVo> list = memberTicketMapper.listPageTicketByElecStationId(member.getMemberId(), elecStationId, usingStatus);
        return new PageInfo<>(list);
    }

    @Override
    public MemberTicket selectByTicketWithMember(Long memberId, Long ticketTypeId) {

        MemberTicketExample memberTicketExample = new MemberTicketExample();
        memberTicketExample.createCriteria().andMemberIdEqualTo(memberId).andTicketTypeIdEqualTo(ticketTypeId);

        return memberTicketMapper.selectByExample(memberTicketExample).stream().findFirst().orElseGet(() -> null);
    }

    /**
     * 用户直接领取获得优惠券
     *
     * @param ticketTypeId
     * @param memberId
     */
    @Override
    public void addTicket(Long ticketTypeId, Long memberId) {
        //发送记录增加
        MemberInfo memberInfo = memberInfoService.selectByPrimaryKey(memberId);
        TenantTicketType tenantTicketType = tenantTicketTypeService.selectByPrimaryKey(ticketTypeId);
        TenantTicketSendRecord tenantTicketSendRecord = new TenantTicketSendRecord();
        tenantTicketSendRecord.setTenantCode(memberInfo.getTenantCode());
        tenantTicketSendRecord.setActivityMemberId(null);
        tenantTicketSendRecord.setTicketTypeId(tenantTicketType.getTicketTypeId());
        tenantTicketSendRecord.setSendCount(1);
        tenantTicketSendRecord.setSendTime(new Date());
        tenantTicketSendRecord.setSendType("0");
        tenantTicketSendRecord.setCreatedBy(memberInfo.getTenantCode());
        tenantTicketSendRecord.setCreatedTime(new Date());
        tenantTicketSendRecordMapper.insertReturnId(tenantTicketSendRecord);

        Calendar calendar = Calendar.getInstance();
        MemberTicket memberTicket = new MemberTicket();
        memberTicket.setMemberId(memberInfo.getMemberId());
        memberTicket.setTicketTypeId(tenantTicketType.getTicketTypeId());
        memberTicket.setGainTime(new Date());
        if (WebConstant.CON0.equals(tenantTicketType.getEffectType())) {
            calendar.add(Calendar.DAY_OF_MONTH, tenantTicketType.getEffectDay());
            memberTicket.setEndTime(calendar.getTime());
        } else {
            memberTicket.setEndTime(tenantTicketType.getEffectEndDate());
        }
        memberTicket.setTicketSendRecordId(tenantTicketSendRecord.getTicketSendRecordId());
        memberTicket.setStatus(WebConstant.CON0);
        memberTicket.setTicketSource("6");
        memberTicket.setCreatedBy(memberInfo.getTenantCode());
        memberTicket.setCreatedTime(new Date());
        memberTicket.setTenantCode(memberInfo.getTenantCode());
        memberTicketMapper.insertSelective(memberTicket);

        //减少剩余次数
        tenantTicketType.setRemainTicket(tenantTicketType.getRemainTicket()-1);
        tenantTicketTypeService.updateByPrimaryKey(tenantTicketType);

    }

    @Override
    public int listByTicketWithMember(Long memberId, Long ticketTypeId) {
        MemberTicketExample memberTicketExample = new MemberTicketExample();
        memberTicketExample.createCriteria().andMemberIdEqualTo(memberId).andTicketTypeIdEqualTo(ticketTypeId);

        return memberTicketMapper.selectByExample(memberTicketExample).size();
    }

    public MarketActivityMember marketActivityMemberAdd(MemberInfo memberInfo, MarketActivityTicket marketActivityTicket, Long rechargeOrderId) {
        //MarketActivityMember记录+1 营销活动记录增加
        MarketActivityMember marketActivityMember = new MarketActivityMember();
        marketActivityMember.setTenantCode(memberInfo.getTenantCode());
        marketActivityMember.setMemberId(memberInfo.getMemberId());

        marketActivityMember.setMarketActivityId(marketActivityTicket.getMarketActivityId());
        //一个营销活动多张优惠券时不录入id
        //marketActivityMember.setTicketTypeId(tenantTicketType.getTicketTypeId());
        marketActivityMember.setGainCount(1);
        marketActivityMember.setCreatedTime(new Date());
        marketActivityMember.setCreatedBy("MINI" + memberInfo.getTenantCode());
        marketActivityMember.setRechargeOrderId(rechargeOrderId);
        //marketActivityMemberService.insert(marketActivityMember);
        marketActivityMemberMapper.insertReturnId(marketActivityMember);
        return marketActivityMember;

    }


    //优惠劵记录增加，发送记录增加，营销活动记录增加
    public void allTicketDataAdd(MemberInfo memberInfo, TenantTicketType tenantTicketType, MarketActivityTicket marketActivityTicket, Long rechargeOrderId, MarketActivityMember marketActivityMember) {
        //发送记录增加
        TenantTicketSendRecord tenantTicketSendRecord = new TenantTicketSendRecord();
        tenantTicketSendRecord.setTenantCode(memberInfo.getTenantCode());
        tenantTicketSendRecord.setActivityMemberId(marketActivityMember.getActivityMemberId());
        tenantTicketSendRecord.setTicketTypeId(tenantTicketType.getTicketTypeId());
        tenantTicketSendRecord.setSendCount(marketActivityTicket.getSendCount());
        tenantTicketSendRecord.setSendTime(new Date());
        tenantTicketSendRecord.setSendType("0");
        tenantTicketSendRecord.setCreatedBy("MINI" + memberInfo.getTenantCode());
        tenantTicketSendRecord.setCreatedTime(new Date());
        tenantTicketSendRecordMapper.insertReturnId(tenantTicketSendRecord);

        //优惠券发放次数 优惠劵记录增加
        insertTicketData(tenantTicketType, marketActivityTicket.getSendCount(), memberInfo, tenantTicketSendRecord);

    }

    public void insertTicketData(TenantTicketType ticketType, int count, MemberInfo memberInfo, TenantTicketSendRecord tenantTicketSendRecord) {
        if (ticketType != null) {
            for (int i = 0; i < count; i++) {
                Calendar calendar = Calendar.getInstance();
                MemberTicket memberTicket = new MemberTicket();
                memberTicket.setMemberId(memberInfo.getMemberId());
                memberTicket.setTicketTypeId(ticketType.getTicketTypeId());
                memberTicket.setGainTime(new Date());
                if (WebConstant.CON0.equals(ticketType.getEffectType())) {
                    calendar.add(Calendar.DAY_OF_MONTH, ticketType.getEffectDay());
                    memberTicket.setEndTime(calendar.getTime());
                } else {
                    memberTicket.setEndTime(ticketType.getEffectEndDate());
                }
                memberTicket.setTicketSendRecordId(tenantTicketSendRecord.getTicketSendRecordId());
                memberTicket.setStatus(WebConstant.CON0);
                memberTicket.setTicketSource(WebConstant.CON1);
                memberTicket.setCreatedBy("MINI" + memberInfo.getTenantCode());
                memberTicket.setCreatedTime(new Date());
                memberTicket.setTenantCode(memberInfo.getTenantCode());
                memberTicketMapper.insertSelective(memberTicket);
            }
        }
    }

}
